package com.linln.wxapi;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.linln.common.enums.TypeEnum;
import com.linln.common.utils.DateUtils;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.member.domain.AreaCount;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberCollect;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.service.AreaCountService;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberCollectService;
import com.linln.modules.member.service.MemberInfoService;
import com.linln.modules.message.domain.MessageInfo;
import com.linln.modules.store.domain.StoreSet;
import com.linln.modules.store.domain.StoreTop;
import com.linln.modules.store.domain.Storeinfo;
import com.linln.modules.store.domain.Type;
import com.linln.modules.store.service.StoreSetService;
import com.linln.modules.store.service.StoreTopService;
import com.linln.modules.store.service.StoreinfoService;
import com.linln.modules.store.service.TypeService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 商户相关小程序接口
 * @author hct
 *
 */
@Api(value="商户信息管理")
@RestController
@RequestMapping("/wx/store/{area}")
public class WxApiSoreController {
	
	  @Autowired
	  private StoreinfoService baseinfoService;
	  @Autowired
	  private TypeService typeService;
	  @Autowired
	  private MemberCollectService  memberCollectService;
	  @Autowired
	  private MemberAgentService  memberAgentService;


	  
	  @Autowired
	  private StoreSetService storeSetService;
	  @Autowired
	  private MemberInfoService memberInfoService;
	
	  @Autowired
	  private StoreTopService topService;
	  @Autowired
	  private AreaCountService areaCountService;
   
	  private final Logger logger = LoggerFactory.getLogger(this.getClass());
   
   /**
     * 获取商户分类信息
     * @param appid
     * @param code
     * @return
     */
     @ApiOperation(value = "获取商户分类信息",  notes = "获取商户分类信息")
     @RequestMapping(value = "type",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo storetype(@PathVariable String area) {
        
         try {
         	// 创建匹配器，进行动态查询匹配
             ExampleMatcher matcher = ExampleMatcher.matching()
                     .withMatcher("title", match -> match.contains());
             Type type=new Type();
             //type.setPid(0l);
             // 获取数据列表
             Example<Type> example = Example.of(type, matcher);
             Sort sort = new Sort(Sort.Direction.ASC, "num");
             List<Type> list = typeService.getListByExample(example, sort);
             return ResultVoUtil.success(list);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
   
     
     /**
      * 获取热门商户信息
      * @param area 区域
      * @param lng  经度
      * @param lat  纬度
      * @return
      */
     @ApiOperation(value = "获取热门商户列表信息",  notes = "获取热门商户列表信息")
     @RequestMapping(value = "hotlist",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo storehotlist(@PathVariable String area,
    		 @RequestParam(value = "pageNumber", required = false,defaultValue="1") Integer pageNumber,
  			@RequestParam(value = "pageSize", required = false,defaultValue="20") Integer pageSize) {
       	System.out.println(DateUtils.format(new Date())+"storehotlist area>>"+area);

         try {
         	// 创建匹配器，进行动态查询匹配
             ExampleMatcher matcher = ExampleMatcher.matching()
                     .withMatcher("store_name", match -> match.contains());
             Storeinfo baseinfo=new Storeinfo();
             baseinfo.setArea(area); 
             baseinfo.setStoreStatus(1); 
             Example<Storeinfo> example = Example.of(baseinfo, matcher);
             Page<Storeinfo> list = baseinfoService.getPageList(example, pageNumber,pageSize);
             
             if(list.getContent()==null || list.getContent().size()==0) {
                 return ResultVoUtil.success("暂无数据"); 

             }else {
               Map<String,Object> map=new HashMap<String,Object>();
              map.put("list", list.getContent());
              map.put("pageNumber", list.getPageable().getPageNumber()+1);
              map.put("pageSize", list.getPageable().getPageSize());
              map.put("pageCount", list.getTotalPages());
              map.put("allCount", list.getTotalElements());
              return ResultVoUtil.success(map);
             }
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
              return ResultVoUtil.error("接口异常"); 
         }
  
     }
     
  
     /**
      * 获取热门商户信息
      * @param area 区域
      * @param lng  经度
      * @param lat  纬度
      * @return
      */
     @ApiOperation(value = "获取商户列表信息",  notes = "获取商户列表信息")
     @RequestMapping(value = "list",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo storelist(@PathVariable String area,String store_name,Integer typetwo,
    		 @RequestParam(value = "pageNumber", required = false,defaultValue="1") Integer pageNumber,
 			@RequestParam(value = "pageSize", required = false,defaultValue="20") Integer pageSize,
 			Long type) {
        
         try {
         	// 创建匹配器，进行动态查询匹配
             ExampleMatcher matcher = ExampleMatcher.matching()
                     .withMatcher("store_name", match -> match.contains());
             Storeinfo baseinfo=new Storeinfo();
             baseinfo.setArea(area); 
             baseinfo.setStoreStatus(1); 

              // 获取数据列表
             Type storetype=new Type();
             if(type!=null && type>0) {
            	 storetype.setId(type);
            	 baseinfo.setStoretype(storetype);
             }
             Sort sort = new Sort(Sort.Direction.DESC, "id");
             if(typetwo!=null && typetwo==1) {
             	 //热门
                 sort= new Sort(Sort.Direction.DESC, "readnum");
             }else if(typetwo!=null && typetwo==2) {
            	 //附近
            	 sort= new Sort(Sort.Direction.DESC, "id");
             }
 
             Example<Storeinfo> example = Example.of(baseinfo, matcher);
             Page<Storeinfo> list = baseinfoService.getPageList(example,sort, pageNumber,pageSize);
             
             if(list.getContent()==null || list.getContent().size()==0) {
                 return ResultVoUtil.success("暂无数据"); 

             }else {
               Map<String,Object> map=new HashMap<String,Object>();
              map.put("list", list.getContent());
              map.put("pageNumber", list.getPageable().getPageNumber()+1);
              map.put("pageSize", list.getPageable().getPageSize());
              map.put("pageCount", list.getTotalPages());
              map.put("allCount", list.getTotalElements());
              return ResultVoUtil.success(map);
             }
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
              return ResultVoUtil.error("接口异常"); 
         }
  
     }


    /**
     *
     * @param area
     * @param keyword
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "搜索商户信息搜索商户信息",  notes = "获取热门商户列表信息")
    @RequestMapping(value = "search",method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResultVo searchStore(@PathVariable String area,String keyword,
    		 @RequestParam(value = "pageNumber", required = false,defaultValue="1") Integer pageNumber,
  			@RequestParam(value = "pageSize", required = false,defaultValue="20") Integer pageSize
  			) {
        System.out.println(DateUtils.format(new Date()) + "storehotlist area>>" + area);

        try {
            // 创建匹配器，进行动态查询匹配
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("store_name", match -> match.contains());
            Storeinfo baseinfo = new Storeinfo();
            if (StringUtils.isNoneBlank(keyword)) {
                baseinfo.setStore_name(keyword);
            }
            baseinfo.setArea(area);
            baseinfo.setStoreStatus(1);
            Example<Storeinfo> example = Example.of(baseinfo, matcher);
            Page<Storeinfo> list = baseinfoService.getPageList(example, pageNumber, pageSize);

            if (list.getContent() == null || list.getContent().size() == 0) {
                return ResultVoUtil.success("暂无数据");

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("list", list.getContent());
                map.put("keyword", keyword);
                map.put("pageNumber", list.getPageable().getPageNumber() + 1);
                map.put("pageSize", list.getPageable().getPageSize());
                map.put("pageCount", list.getTotalPages());
                map.put("allCount", list.getTotalElements());
                return ResultVoUtil.success(map);
            }
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("接口异常");
        }

    }



        /**
         * 获取热门商户信息
         * @param area 区域
         * @param lng  经度
         * @param lat  纬度
         * @return
         */
     @ApiOperation(value = "获取我的商户列表信息",  notes = "获取我的商户列表信息")
     @RequestMapping(value = "mylist",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo mystorelist(@PathVariable String area,Long memberId,String keyword,
    		 @RequestParam(value = "pageNumber", required = false,defaultValue="1") Integer pageNumber,
  			 @RequestParam(value = "pageSize", required = false,defaultValue="20") Integer pageSize
    		 ) {
        
         try {
        	 
    		 Storeinfo baseinfo=new Storeinfo();
        	
        	 if(keyword!=null && !"".equals(keyword)){
        	     baseinfo.setStore_name(keyword);
 			} 
        	baseinfo.setStoreStatus(1);
   			baseinfo.setIstop(1);
   			baseinfo.setPayStatus(1);
         	
        	 MemberAgent memberAgent= memberAgentService.getByMemberIdAndArea(memberId, area);
             Page<Storeinfo> list = null;
             ExampleMatcher matcher = ExampleMatcher.matching()
  					.withMatcher("store_name", match -> match.contains());
  			 Example<Storeinfo> examplenone=null;

        	 if(memberAgent!=null) {
      			baseinfo.setArea(area);
      			examplenone = Example.of(baseinfo, matcher);
      			list=baseinfoService.getPageList(examplenone, pageNumber, pageSize);
        	 }else {
        		 
    			MemberInfo memberInfo=new MemberInfo();
      			memberInfo.setId(memberId);
      			baseinfo.setMember(memberInfo);
      			examplenone = Example.of(baseinfo, matcher);
      			list=baseinfoService.getPageList(examplenone, pageNumber, pageSize);
                 	 
        	 }
             Map<String,Object> map=new HashMap<String,Object>();  
        	 map.put("list", list.getContent());
             map.put("pageNumber", list.getPageable().getPageNumber()+1);
             map.put("pageSize", list.getPageable().getPageSize());
             map.put("pageCount", list.getTotalPages());
             map.put("allCount", list.getTotalElements());
         	 return ResultVoUtil.success(map);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
              return ResultVoUtil.error("接口异常"); 
         }
  
     }
     
     
     
	  /**
      * 收藏及取消收藏
      * @param area 区域
      * @param lng  经度
      * @param lat  纬度
      * @return
      */
     @ApiOperation(value = "是否收藏",  notes = "是否收藏")
     @RequestMapping(value = "iscollect",method= {RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo mymessagecollect(@PathVariable String area,Long storeId, Long memberId) {
        
         try {
         	MemberCollect collect= memberCollectService.getByMemberIdAndTypeId(memberId,TypeEnum.STORE.getCode(), storeId);
             
         	if(collect!=null && collect.getId()>0){
         		return ResultVoUtil.success(1);
        	}       
        	return ResultVoUtil.success(0); 	
         } catch (Exception e) {
             	return ResultVoUtil.error("失败"); 
          }

    }
    
    /**
     * 编辑商户信息
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "申请商户",  notes = "申请商户")
    @RequestMapping(value = "apply",method=RequestMethod.POST)
    @ResponseBody
    public ResultVo storefabu(@PathVariable String area,Storeinfo baseinfo,
    		Long memberId,Long storetype_id
    		) {
       
        try {
            
        	System.out.println("baseinfo.getStartTime()>>"+baseinfo.getStartTime());
        	System.out.println("baseinfo.getDay()=="+baseinfo.getDay());
        	Gson gson=new Gson();
        	String ss=gson.toJson(baseinfo);
        	System.out.println("ss"+ss);
            baseinfo.setStoreStatus(1);
        	if(baseinfo.getIstop()==1) {
        	baseinfo.setEndTime(DateUtils.getDateInfo(baseinfo.getStartTime(),baseinfo.getDay()));
            baseinfo.setStoreStatus(0);

        	}
        	if(storetype_id!=null && storetype_id>0) {
            Type storetype =new Type();
            storetype.setId(storetype_id);
        	baseinfo.setStoretype(storetype);
        	}
        	if(memberId!=null && memberId>0) {
            	MemberInfo member =new MemberInfo();
            	member.setId(memberId);
            	baseinfo.setMember(member);
            	}
        	 baseinfo.setStore_star(3);
             baseinfo.setZannum(0);
             baseinfo.setSharenum(0);
             baseinfo.setReadnum(0);
             baseinfo.setCollectnum(0);
             baseinfo.setPayStatus(0);
             baseinfo.setOrderId(ToolUtil.getRandomString(32));
             baseinfo = baseinfoService.saveAndSendNotice(baseinfo);
             return ResultVoUtil.success(baseinfo);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("申请失败");
        }
 
    }


    /**
     * 申请商户
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "编辑商户信息",  notes = "申请商户")
    @RequestMapping(value = "edit",method=RequestMethod.POST)
    @ResponseBody
    public ResultVo storeedit(@PathVariable String area,Storeinfo baseinfo,
                              Long memberId,Long storetype_id,String adStartTime
    ) {

        try {

            System.out.println("baseinfo.getStartTime()>>"+baseinfo.getStartTime());
            System.out.println("baseinfo.getDay()=="+baseinfo.getDay());
            baseinfo.setStoreStatus(1);
            Storeinfo storeinfoold=baseinfoService.getById(baseinfo.getId());
        	MemberInfo memberold=memberInfoService.getById(memberId);
            storeinfoold.setStoreStatus(1);
            if(memberold!=null && memberold.getIsagent().intValue()==1) {
                if(storeinfoold.getIstop().intValue() > 0){
                    if(StringUtils.isNotEmpty(baseinfo.getOrderCode())){
                        storeinfoold.setOrderId(baseinfo.getOrderCode());
                        storeinfoold.setIstop(baseinfo.getIstop());
                        storeinfoold.setDay(baseinfo.getDay());
                        BigDecimal b1 = new BigDecimal(storeinfoold.getFee());
                        BigDecimal b2 = new BigDecimal(baseinfo.getFee());
                        Double addFee = b1.add(b2).doubleValue();
                        storeinfoold.setFee(addFee);
                        Date now=new Date();
						 if(storeinfoold.getEndTime().before(now)) {
							 storeinfoold.setEndTime(DateUtils.getDateInfo(now, storeinfoold.getDay()));
						 }else {
                        storeinfoold.setEndTime(DateUtils.getDateInfo(storeinfoold.getEndTime(),storeinfoold.getDay()));
						 }
                    }
                }
                Date oldStartime=storeinfoold.getStartTime();
                String dateinfo=DateUtils.format(oldStartime, "yyyy-MM-dd");
                String dateinfoss=dateinfo+" "+adStartTime;
                Date newStartTime=DateUtils.strToDate(dateinfoss, "yyyy-MM-dd hh:mm");
                storeinfoold.setStartTime(newStartTime);
            }
            else {
                storeinfoold.setPushName(baseinfo.getPushName());
                storeinfoold.setAddress(baseinfo.getPushName());
                storeinfoold.setCity(baseinfo.getCity());
                storeinfoold.setStore_tel(baseinfo.getStore_tel());
            }
            storeinfoold.setStore_name(baseinfo.getStore_name());
            storeinfoold.setLogo(baseinfo.getLogo());
            storeinfoold.setYyzz_img(baseinfo.getYyzz_img());
            storeinfoold.setYyzz_code(baseinfo.getYyzz_code());
            storeinfoold.setYingye_time(baseinfo.getYingye_time());
            storeinfoold.setStore_img(baseinfo.getStore_img());
            storeinfoold.setSfz_img(baseinfo.getSfz_img());
            storeinfoold.setDetails(baseinfo.getDetails());
            storeinfoold = baseinfoService.save(storeinfoold);
            //商户发布数量
            return ResultVoUtil.success(storeinfoold);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return ResultVoUtil.error("编辑失败");
        }

    }

    
    /**
     * 商户收藏及取消收藏
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "收藏商户",  notes = "收藏商户")
    @RequestMapping(value = "collect",method= {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResultVo storecollect(@PathVariable String area,Long storeId, Long memberId) {
       
        try {
        	
        	MemberCollect collect= memberCollectService.getByMemberIdAndTypeId(memberId, TypeEnum.STORE.getCode(),storeId);
            
        	if(collect!=null && collect.getId()>0){
        		memberCollectService.delCollect(collect.getId());
        		//取消收藏
        	}else{
        		collect=new MemberCollect();
        		collect.setArea(area);
        		collect.setCreateDate(new Date());
        		collect.setType(TypeEnum.STORE.getCode());
        		collect.setTypeId(storeId);
        		collect.setMemberId(memberId);
            	collect = memberCollectService.save(collect);
            	baseinfoService.updateIsCollectAddById(storeId);

            	AreaCount count=areaCountService.findByArea(area);
        		if(count==null) {
        			count=new AreaCount();
        			count.setArea(area);
        			count.setStore_collectnum(1); 
        			areaCountService.save(count);
        		}else {
        			areaCountService.updateCollectByArea(area);
        		}
 
        	}         	
        	 return ResultVoUtil.success(collect);
        } catch (Exception e) {
        	return ResultVoUtil.error("失败"); 
        }
 
    }
    /**
     * 获取商户详情
     * @param area 区域
     * @param lng  经度
     * @param lat  纬度
     * @return
     */
    @ApiOperation(value = "获取商户详情",  notes = "获取商户详情信息")
    @RequestMapping(value = "detail",method= {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResultVo storedetail(@PathVariable String area,Long id) {
       
        try {
        	  Storeinfo baseinfo = baseinfoService.getById(id);
        	  //baseinfo.setReadnum(baseinfo.getReadnum()+1);
        	  baseinfoService.updateIsReadAddById(id);
        	//统计访问量
        	  AreaCount count=areaCountService.findByArea(area);
          	if(count==null) {
          		count=new AreaCount();
          		count.setArea(area);
          		count.setStore_readnum(1);
          		areaCountService.save(count);
          	}else {
        	  areaCountService.updateReadNumByArea(area);
          	}
        	 return ResultVoUtil.success(baseinfo);

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
        }
 
    }
    
    /**
     * 获取商户设置基础信息
     * @param area 区域
   
     * @return
     */
    @ApiOperation(value = "获取商户设置信息",  notes = "获取商户设置信息")
    @RequestMapping(value = "storeset",method= {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public ResultVo storeset(@PathVariable String area ) {
       
        try {
        	StoreSet set=storeSetService.getById(1L);
            return ResultVoUtil.success(set);

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
         	 return ResultVoUtil.error("失败");

        }
 
    }
    
    
    /**
     * 获取置顶信息
* @param area 区域

* @return
*/
@ApiOperation(value = "获取信息设置信息",  notes = "获取信息设置信息")
@RequestMapping(value = "storetop",method= {RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public ResultVo storetop(@PathVariable String area ) {

try {
	// 创建匹配器，进行动态查询匹配
    ExampleMatcher matcher = ExampleMatcher.matching()
            .withMatcher("title", match -> match.contains());
    StoreTop baseinfo=new StoreTop();
    // 获取数据列表
    Example<StoreTop> example = Example.of(baseinfo, matcher);

    List<StoreTop> list=topService.getList(example);
    return ResultVoUtil.success(list);

} catch (Exception e) {
this.logger.error(e.getMessage(), e);
	 return ResultVoUtil.error("失败");

}

}
    
}

    

